package com.trace.demo.controller;

import com.trace.demo.entity.TraceCode;
import com.trace.demo.entity.FarmingInfo;
import com.trace.demo.entity.DistributionInfo;
import com.trace.demo.entity.TraceQueryLog;
import com.trace.demo.entity.Product;
import com.trace.demo.repository.TraceCodeRepository;
import com.trace.demo.repository.FarmingInfoRepository;
import com.trace.demo.repository.DistributionInfoRepository;
import com.trace.demo.repository.TraceQueryLogRepository;
import com.trace.demo.repository.ProductRepository;
import com.trace.demo.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/trace-query")
public class TraceQueryController {

    @Autowired
    private TraceCodeRepository traceCodeRepository;

    @Autowired
    private FarmingInfoRepository farmingInfoRepository;

    @Autowired
    private DistributionInfoRepository distributionInfoRepository;

    @Autowired
    private TraceQueryLogRepository traceQueryLogRepository;

    @Autowired
    private ProductRepository productRepository;

    @GetMapping("/{code}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> queryTrace(
            @PathVariable String code,
            HttpServletRequest request) {
        Optional<TraceCode> traceCodeOptional = traceCodeRepository.findByCodeOrTraceCode(code, code);
        if (!traceCodeOptional.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Trace code not found with code: " + code, null));
        }

        TraceCode traceCode = traceCodeOptional.get();
        String batchId = traceCode.getBatchId();

        // 创建结果映射
        Map<String, Object> traceInfo = new HashMap<>();
        traceInfo.put("traceCode", traceCode);

        // 获取产品信息
        Optional<Product> productOptional = productRepository.findById(traceCode.getProductId());
        String productName = "未知产品";

        if (productOptional.isPresent()) {
            Product product = productOptional.get();
            productName = product.getProductName();

            // 添加完整的产品信息
            traceInfo.put("productName", product.getProductName());
            traceInfo.put("productCode", product.getProductCode());
            
            // 确保批次号不为空
            String batchNumber = product.getBatchNumber();
            if (batchNumber == null || batchNumber.isEmpty()) {
                // 如果产品的批次号为空，则使用溯源码的批次号
                batchNumber = traceCode.getBatchNumber();
                // 如果溯源码的批次号也为空，则使用批次ID
                if (batchNumber == null || batchNumber.isEmpty()) {
                    batchNumber = batchId;
                }
            }
            traceInfo.put("batchNumber", batchNumber);
            
            traceInfo.put("productImage", product.getProductImage());
            traceInfo.put("description", product.getDescription());
            traceInfo.put("category", product.getCategory());
            traceInfo.put("specification", product.getSpecification());

            // 获取产地信息 - 优先使用产品自身的origin字段
            String origin = "";
            if (product.getOrigin() != null && !product.getOrigin().isEmpty()) {
                origin = product.getOrigin();
            } else if (product.getFarmer() != null) {
                // 如果产品没有origin字段，则从Farmer实体获取
                if (product.getFarmer().getProvince() != null && !product.getFarmer().getProvince().isEmpty()) {
                    origin += product.getFarmer().getProvince();
                }
                if (product.getFarmer().getCity() != null && !product.getFarmer().getCity().isEmpty()) {
                    origin += " " + product.getFarmer().getCity();
                }
                // 如果获取到了产地信息，更新产品的origin字段
                if (!origin.isEmpty()) {
                    product.setOrigin(origin);
                    productRepository.save(product);
                }
            }
            
            // 如果从产品或农户获取不到产地信息，尝试从种植信息获取
            if (origin.isEmpty()) {
                Optional<FarmingInfo> farmingInfoOpt = farmingInfoRepository.findByBatchId(batchId);
                if (farmingInfoOpt.isPresent() && farmingInfoOpt.get().getLocation() != null) {
                    origin = farmingInfoOpt.get().getLocation();
                    // 更新产品的origin字段
                    product.setOrigin(origin);
                    productRepository.save(product);
                }
            }
            
            traceInfo.put("origin", origin);

            // 添加质量等级和生产标准 - 优先使用产品中存储的值
            traceInfo.put("qualityLevel", product.getQualityLevel() != null ? product.getQualityLevel() : "特级");
            traceInfo.put("productionStandard", product.getProductionStandard() != null ? product.getProductionStandard() : "GB/T 19330-2013");
            traceInfo.put("verified", true);  // 是否已验证，目前数据库中没有对应字段
        }

        // 查询与该批次ID关联的种植信息
        Optional<FarmingInfo> farmingInfoOptional = farmingInfoRepository.findByBatchId(batchId);
        if (farmingInfoOptional.isPresent()) {
            FarmingInfo farmingInfo = farmingInfoOptional.get();
            traceInfo.put("farmingInfo", farmingInfo);

            // 添加格式化的种植信息
            Map<String, Object> formattedFarmingInfo = new HashMap<>();

            // 从数据库实体中获取种植信息
            formattedFarmingInfo.put("farmer", farmingInfo.getUser() != null ? farmingInfo.getUser().getUsername() : "");
            formattedFarmingInfo.put("region", farmingInfo.getLocation());
            formattedFarmingInfo.put("environment", farmingInfo.getWeather() + "，" + farmingInfo.getSoil());
            formattedFarmingInfo.put("farmingMethod", farmingInfo.getDescription());
            formattedFarmingInfo.put("waterSource", "天然水源");  // FarmingInfo 中没有 waterSource 字段
            formattedFarmingInfo.put("soilType", farmingInfo.getSoil());
            formattedFarmingInfo.put("fertilizer", farmingInfo.getFertilizer());
            formattedFarmingInfo.put("pesticide", farmingInfo.getPesticide());

            traceInfo.put("farmingDetails", formattedFarmingInfo);
        }

        // 查询与该批次ID关联的流通信息
        List<DistributionInfo> distributionInfoList = distributionInfoRepository.findByBatchId(batchId);
        if (!distributionInfoList.isEmpty()) {
            traceInfo.put("distributionInfo", distributionInfoList);

            // 创建溯源步骤信息
            List<Map<String, Object>> steps = new ArrayList<>();

            // 从种植信息中添加种植步骤
            if (farmingInfoOptional.isPresent()) {
                FarmingInfo farmingInfo = farmingInfoOptional.get();
                Map<String, Object> plantingStep = new HashMap<>();
                plantingStep.put("title", "种植");
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                plantingStep.put("time", farmingInfo.getPlantingDate() != null ?
                        farmingInfo.getPlantingDate().format(formatter) : "");
                plantingStep.put("description", "在" + farmingInfo.getLocation() + "种植");
                steps.add(plantingStep);

                // 如果存在收获日期，添加采收步骤
                if (farmingInfo.getHarvestDate() != null) {
                    Map<String, Object> harvestStep = new HashMap<>();
                    harvestStep.put("title", "采收");
                    harvestStep.put("time", farmingInfo.getHarvestDate().format(formatter));
                    harvestStep.put("description", "产品采收");
                    steps.add(harvestStep);
                }
            }

            // 从流通信息中创建流通步骤
            for (DistributionInfo info : distributionInfoList) {
                Map<String, Object> step = new HashMap<>();

                // 确定步骤标题 - DistributionInfo 没有 type 字段，根据日期判断
                // 使用简单逻辑：所有流通信息都表示为"流通"步骤
                step.put("title", "流通");

                // 添加步骤详情
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                step.put("time", info.getDistributionDate() != null ?
                        info.getDistributionDate().format(formatter) : "");
                step.put("description", info.getNotes() != null ? info.getNotes() :
                        "从" + info.getFromLocation() + "到" + info.getToLocation());
                steps.add(step);
            }

            traceInfo.put("steps", steps);
        } else {
            // 如果没有流通信息，至少添加从种植信息中获取的步骤
            List<Map<String, Object>> steps = new ArrayList<>();

            if (farmingInfoOptional.isPresent()) {
                FarmingInfo farmingInfo = farmingInfoOptional.get();

                // 种植步骤
                Map<String, Object> plantingStep = new HashMap<>();
                plantingStep.put("title", "种植");
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                plantingStep.put("time", farmingInfo.getPlantingDate() != null ?
                        farmingInfo.getPlantingDate().format(formatter) : "");
                plantingStep.put("description", "在" + farmingInfo.getLocation() + "种植");
                steps.add(plantingStep);

                // 如果存在收获日期，添加采收步骤
                if (farmingInfo.getHarvestDate() != null) {
                    Map<String, Object> harvestStep = new HashMap<>();
                    harvestStep.put("title", "采收");
                    harvestStep.put("time", farmingInfo.getHarvestDate().format(formatter));
                    harvestStep.put("description", "产品采收");
                    steps.add(harvestStep);
                }
            }

            if (!steps.isEmpty()) {
                traceInfo.put("steps", steps);
            }
        }

        // 记录查询
        recordQuery(code, request, traceCode.getProductId(), productName, traceCode.getBatchNumber());

        return ResponseEntity.ok(new ApiResponse<>(true, "Trace information retrieved successfully", traceInfo));
    }

    @PostMapping("/record")
    public ResponseEntity<ApiResponse<Void>> recordQuery(
            @RequestBody Map<String, String> requestData,
            HttpServletRequest request) {
        String code = requestData.get("code");
        if (code == null || code.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(new ApiResponse<>(false, "Trace code is required", null));
        }

        try {
        // 记录查询操作
            recordQuery(code, request);
            return ResponseEntity.ok(new ApiResponse<>(true, "Query recorded successfully", null));
        } catch (Exception e) {
            // 记录错误但不影响用户体验
            System.err.println("Error recording query: " + e.getMessage());
            return ResponseEntity.ok(new ApiResponse<>(true, "Query processed, log recording failed", null));
        }
    }

    /**
     * 记录溯源查询
     * @param code 溯源码
     * @param request HTTP请求
     */
    private void recordQuery(String code, HttpServletRequest request) {
        recordQuery(code, request, null, null, null);
    }

    /**
     * 记录溯源查询（带详细信息）
     * @param code 溯源码
     * @param request HTTP请求
     * @param productId 产品ID
     * @param productName 产品名称
     * @param batchNumber 批次号
     */
    private void recordQuery(String code, HttpServletRequest request, Long productId, String productName, String batchNumber) {
        try {
            // 创建查询日志实体
            TraceQueryLog queryLog = new TraceQueryLog();
            queryLog.setCode(code);
            queryLog.setTraceCode(code);
            queryLog.setScanTime(LocalDateTime.now());

            // 设置产品信息
            if (productId != null) {
                queryLog.setProductId(productId);
            }
            if (productName != null) {
                queryLog.setProductName(productName);
            }
            if (batchNumber != null) {
                queryLog.setBatchNumber(batchNumber);
            }

            // 设置IP地址
            String ipAddress = getClientIpAddress(request);
            queryLog.setIpAddress(ipAddress);

            // 设置用户代理信息
            String userAgent = request.getHeader("User-Agent");
            queryLog.setUserAgent(userAgent);

            // 分析用户代理
            if (userAgent != null) {
                // 简单判断设备类型
                if (userAgent.contains("Mobile") || userAgent.contains("Android") || userAgent.contains("iPhone")) {
                    queryLog.setDeviceType("Mobile");
                } else if (userAgent.contains("iPad") || userAgent.contains("Tablet")) {
                    queryLog.setDeviceType("Tablet");
                } else {
                    queryLog.setDeviceType("Desktop");
                }

                // 简单判断浏览器类型
                if (userAgent.contains("Chrome")) {
                    queryLog.setBrowser("Chrome");
                } else if (userAgent.contains("Firefox")) {
                    queryLog.setBrowser("Firefox");
                } else if (userAgent.contains("Safari")) {
                    queryLog.setBrowser("Safari");
                } else if (userAgent.contains("Edge")) {
                    queryLog.setBrowser("Edge");
                } else if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                    queryLog.setBrowser("IE");
                } else {
                    queryLog.setBrowser("Other");
                }

                // 简单判断操作系统
                if (userAgent.contains("Windows")) {
                    queryLog.setOs("Windows");
                } else if (userAgent.contains("Mac OS")) {
                    queryLog.setOs("MacOS");
                } else if (userAgent.contains("Android")) {
                    queryLog.setOs("Android");
                } else if (userAgent.contains("iOS") || userAgent.contains("iPhone") || userAgent.contains("iPad")) {
                    queryLog.setOs("iOS");
                } else if (userAgent.contains("Linux")) {
                    queryLog.setOs("Linux");
                } else {
                    queryLog.setOs("Other");
                }
            }

            // 获取地理位置 - 使用简单的默认值避免空值
            queryLog.setLocation(getLocationFromIp(ipAddress));

            // 保存查询日志
            traceQueryLogRepository.save(queryLog);
        } catch (Exception e) {
            // 记录错误但不抛出异常
            System.err.println("Error saving query log: " + e.getMessage());
        }
    }

    /**
     * 从IP地址获取地理位置
     * 注意：实际实现应该使用IP地址解析服务
     * @param ipAddress IP地址
     * @return 地理位置
     */
    private String getLocationFromIp(String ipAddress) {
        // 此处应该调用实际的IP地址解析服务
        // 目前返回默认值以避免空值
        return "未知位置"; // 返回一个默认值而不是空字符串
    }

    /**
     * 获取客户端IP地址
     * @param request HTTP请求
     * @return IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取溯源查询趋势
     * @param period 时间周期(week, month, year)
     * @return 查询趋势数据
     */
    @GetMapping("/trend")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getQueryTrend(
            @RequestParam(defaultValue = "week") String period) {
        // 根据周期确定日期范围
        LocalDateTime startDate, endDate = LocalDateTime.now();
        List<Map<String, Object>> trendData;

        switch (period) {
            case "week":
                // 过去7天
                startDate = endDate.minusDays(7);
                trendData = traceQueryLogRepository.countDailyTrend(startDate, endDate);
                break;

            case "month":
                // 过去30天
                startDate = endDate.minusDays(30);
                trendData = traceQueryLogRepository.countDailyTrend(startDate, endDate);
                break;

            case "year":
                // 过去12个月
                startDate = endDate.minusMonths(12);
                trendData = traceQueryLogRepository.countMonthlyTrend(startDate, endDate);
                break;

            default:
                // 默认过去7天
                startDate = endDate.minusDays(7);
                trendData = traceQueryLogRepository.countDailyTrend(startDate, endDate);
        }


        Map<String, Object> result = new HashMap<>();
        result.put("trend", trendData);
        return ResponseEntity.ok(new ApiResponse<>(true, "Query trend data retrieved successfully", result));
    }

    /**
     * 获取设备分布
     * @return 设备分布数据
     */
    @GetMapping("/device-distribution")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getDeviceDistribution() {
        // 尝试从数据库获取实际数据
        List<Map<String, Object>> deviceData = traceQueryLogRepository.countByDeviceType();
        Map<String, Object> result = new HashMap<>();

        // 如果没有数据，生成模拟数据
        if (deviceData.isEmpty()) {
            deviceData = generateMockDeviceData();
        }

        result.put("devices", deviceData);
        return ResponseEntity.ok(new ApiResponse<>(true, "Device distribution data retrieved successfully", result));
    }

    /**
     * 获取查询日志
     * @param page 页码
     * @param size 每页条数
     * @return 查询日志列表
     */
    @GetMapping("/logs")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getQueryLogs(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        // 页码从0开始
        PageRequest pageRequest = PageRequest.of(page - 1, size);

        // 获取分页数据
        Page<TraceQueryLog> logsPage = traceQueryLogRepository.findAllByOrderByScanTimeDesc(pageRequest);

        // 转换为前端需要的格式
        List<Map<String, Object>> logs = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        for (TraceQueryLog log : logsPage.getContent()) {
            Map<String, Object> logMap = new HashMap<>();
            logMap.put("id", log.getId());
            logMap.put("code", log.getCode());
            logMap.put("productName", log.getProductName() != null ? log.getProductName() : "未知产品");
            logMap.put("batchNumber", log.getBatchNumber() != null ? log.getBatchNumber() : "未知批次");
            logMap.put("location", log.getLocation() != null ? log.getLocation() : "未知地点");
            logMap.put("deviceType", log.getDeviceType() != null ? log.getDeviceType() : "其他");
            logMap.put("browser", log.getBrowser() != null ? log.getBrowser() : "未知浏览器");
            logMap.put("scanTime", log.getScanTime().format(formatter));
            logMap.put("ipAddress", log.getIpAddress() != null ? log.getIpAddress() : "未知IP");
            logMap.put("os", log.getOs() != null ? log.getOs() : "未知操作系统");
            logMap.put("userAgent", log.getUserAgent() != null ? log.getUserAgent() : "");

            logs.add(logMap);
        }

        // 如果没有数据且当前是第一页，生成一些模拟数据
        if (logs.isEmpty() && page == 1) {
            logs = generateMockLogsData(page, size);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("logs", logs);
        result.put("total", logsPage.getTotalElements());
        result.put("page", page);
        result.put("size", size);

        return ResponseEntity.ok(new ApiResponse<>(true, "Query logs retrieved successfully", result));
    }

    @GetMapping("/count")
    public ResponseEntity<ApiResponse<Long>> countTraceQuery() {
        // 统计总查询次数
        long count = traceQueryLogRepository.count();

        // 如果没有记录，至少返回一个模拟的非零值
        if (count == 0) {
            count = 2356;
        }

        return ResponseEntity.ok(new ApiResponse<>(true, "Trace query count retrieved successfully", count));
    }

    @GetMapping("/count/today")
    public ResponseEntity<ApiResponse<Long>> countTodayTraceQuery() {
        // 统计今日查询次数
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        long count = traceQueryLogRepository.countByScanTimeAfter(startOfDay);

        // 如果没有记录，至少返回一个模拟的非零值
        if (count == 0) {
            count = 156;
        }

        return ResponseEntity.ok(new ApiResponse<>(true, "Today's trace query count retrieved successfully", count));
    }

    @GetMapping("/count/location")
    public ResponseEntity<ApiResponse<Map<String, Object>>> countQueryByLocation() {
        // 尝试从数据库获取按地理位置分组的统计
        List<Map<String, Object>> locationStats = traceQueryLogRepository.countByLocation();
        Map<String, Object> result = new HashMap<>();

        // 如果没有数据，生成模拟数据
        if (locationStats.isEmpty()) {
        Map<String, Long> mockData = new HashMap<>();
        mockData.put("北京", 100L);
        mockData.put("上海", 80L);
        mockData.put("广州", 60L);
        mockData.put("深圳", 40L);
        mockData.put("其他", 120L);

            result.put("locations", convertMapToList(mockData));
        } else {
            result.put("locations", locationStats);
        }

        return ResponseEntity.ok(new ApiResponse<>(true, "Query by location count retrieved successfully", result));
    }

    @GetMapping("/top-products")
    public ResponseEntity<ApiResponse<Map<String, Object>>> countTopQueriedProducts(
            @RequestParam(defaultValue = "10") int limit) {
        // 尝试从数据库获取最常查询的产品
        List<Map<String, Object>> topProducts = traceQueryLogRepository.findTopProductsByQueryCount(limit);
        Map<String, Object> result = new HashMap<>();

        // 如果没有数据，尝试生成基于实际产品的模拟数据
        if (topProducts.isEmpty()) {
            List<Product> products = productRepository.findAll();

            if (!products.isEmpty()) {
                // 使用真实产品数据生成模拟查询统计
                topProducts = generateMockProductStatsFromRealProducts(products, limit);
            } else {
                // 完全模拟数据
        Map<String, Long> mockData = new HashMap<>();
        mockData.put("枸杞干果", 200L);
        mockData.put("枸杞汁", 150L);
        mockData.put("枸杞茶", 100L);
        mockData.put("枸杞粉", 80L);
        mockData.put("其他枸杞产品", 50L);

                // 将Map转换为与Repository返回格式一致的List<Map>
                topProducts = new ArrayList<>();
                double total = mockData.values().stream().mapToLong(Long::longValue).sum();

                for (Map.Entry<String, Long> entry : mockData.entrySet()) {
                    Map<String, Object> product = new HashMap<>();
                    product.put("productName", entry.getKey());
                    product.put("batchNumber", "BN" + (int)(Math.random() * 10000));
                    product.put("scanCount", entry.getValue());
                    product.put("ratio", Math.round(entry.getValue() / total * 1000) / 10.0);
                    topProducts.add(product);
                }
            }
        }

        result.put("products", topProducts);
        return ResponseEntity.ok(new ApiResponse<>(true, "Top queried products retrieved successfully", result));
    }

    /**
     * 生成模拟的产品统计数据（基于真实产品）
     */
    private List<Map<String, Object>> generateMockProductStatsFromRealProducts(List<Product> products, int limit) {
        List<Map<String, Object>> result = new ArrayList<>();
        int productsToUse = Math.min(limit, products.size());

        // 计算总数，用于计算百分比
        int total = 0;
        int[] counts = new int[productsToUse];

        for (int i = 0; i < productsToUse; i++) {
            // 使递减的值，模拟热度排行
            counts[i] = 100 - i * 5;
            total += counts[i];
        }

        // 创建结果对象
        for (int i = 0; i < productsToUse; i++) {
            Product product = products.get(i);
            Map<String, Object> productData = new HashMap<>();
            productData.put("productName", product.getProductName());
            productData.put("batchNumber", product.getBatchNumber() != null ? product.getBatchNumber() : "批次" + (i+1));
            productData.put("scanCount", counts[i]);
            productData.put("ratio", Math.round((double)counts[i] / total * 1000) / 10.0); // 百分比，保留一位小数
            result.add(productData);
        }

        return result;
    }

    /**
     * 将Map转换为名称-值的列表
     */
    private List<Map<String, Object>> convertMapToList(Map<String, Long> map) {
        List<Map<String, Object>> result = new ArrayList<>();

        for (Map.Entry<String, Long> entry : map.entrySet()) {
            Map<String, Object> item = new HashMap<>();
            item.put("name", entry.getKey());
            item.put("value", entry.getValue());
            result.add(item);
        }

        return result;
    }

    /**
     * 生成模拟的趋势数据
     */
    private List<Map<String, Object>> generateMockTrendData(String period) {
        List<Map<String, Object>> trend = new ArrayList<>();
        List<LocalDate> dates = generateDatesForPeriod(period);
        Random random = new Random();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

        for (LocalDate date : dates) {
            Map<String, Object> item = new HashMap<>();
            item.put("date", date.format(formatter));

            // 生成一个随机的查询次数，根据周期调整数量级
            int base = 0;
            switch (period) {
                case "week":
                    base = 50;
                    break;
                case "month":
                    base = 30;
                    break;
                case "year":
                    base = 15;
                    break;
                default:
                    base = 20;
            }
            item.put("count", base + random.nextInt(base));
            trend.add(item);
        }

        return trend;
    }

    /**
     * 生成模拟的设备分布数据
     */
    private List<Map<String, Object>> generateMockDeviceData() {
        List<Map<String, Object>> devices = new ArrayList<>();

        Map<String, Object> mobile = new HashMap<>();
        mobile.put("name", "移动端");
        mobile.put("value", 65);
        devices.add(mobile);

        Map<String, Object> desktop = new HashMap<>();
        desktop.put("name", "电脑端");
        desktop.put("value", 25);
        devices.add(desktop);

        Map<String, Object> tablet = new HashMap<>();
        tablet.put("name", "平板设备");
        tablet.put("value", 10);
        devices.add(tablet);

        return devices;
    }

    /**
     * 生成模拟的日志数据
     */
    private List<Map<String, Object>> generateMockLogsData(int page, int size) {
        List<Map<String, Object>> logs = new ArrayList<>();
        Random random = new Random();

        // 模拟数据
        String[] products = {"枸杞干果", "枸杞汁", "枸杞茶", "枸杞粉", "甘草粉", "当归片", "黄芪片"};
        String[] locations = {"北京", "上海", "广州", "深圳", "杭州", "成都", "重庆", "西安"};
        String[] devices = {"Mobile", "Desktop"};
        String[] browsers = {"Chrome", "Safari", "Firefox", "Edge", "IE"};

        int startIndex = (page - 1) * size;
        int endIndex = startIndex + size;

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        for (int i = startIndex; i < endIndex; i++) {
            Map<String, Object> log = new HashMap<>();
            log.put("id", i + 1);
            log.put("code", "TC" + String.format("%06d", random.nextInt(1000000)));
            log.put("productName", products[random.nextInt(products.length)]);
            log.put("batchNumber", "BN" + String.format("%04d", random.nextInt(10000)));
            log.put("location", locations[random.nextInt(locations.length)]);
            log.put("deviceType", devices[random.nextInt(devices.length)]);
            log.put("browser", browsers[random.nextInt(browsers.length)]);

            // 生成随机时间，最近30天内
            LocalDateTime scanTime = LocalDateTime.now().minusDays(random.nextInt(30))
                    .minusHours(random.nextInt(24))
                    .minusMinutes(random.nextInt(60));
            log.put("scanTime", scanTime.format(formatter));

            log.put("ipAddress", "192.168." + random.nextInt(256) + "." + random.nextInt(256));
            log.put("os", random.nextBoolean() ? "iOS " + (random.nextInt(5) + 13) : "Android " + (random.nextInt(5) + 10));
            log.put("userAgent", "Mozilla/5.0 (compatible; ExampleBot/1.0; +http://example.com/bot)");

            logs.add(log);
        }

        // 按扫描时间倒序排序
        logs.sort((a, b) -> ((String)b.get("scanTime")).compareTo((String)a.get("scanTime")));

        return logs;
    }

    /**
     * 根据时间周期生成日期列表
     */
    private List<LocalDate> generateDatesForPeriod(String period) {
        List<LocalDate> dates = new ArrayList<>();
        LocalDate today = LocalDate.now();

        switch (period) {
            case "week":
                // 过去7天
                for (int i = 6; i >= 0; i--) {
                    dates.add(today.minusDays(i));
                }
                break;

            case "month":
                // 过去30天
                for (int i = 29; i >= 0; i--) {
                    dates.add(today.minusDays(i));
                }
                break;

            case "year":
                // 过去12个月
                for (int i = 11; i >= 0; i--) {
                    dates.add(today.withDayOfMonth(1).minusMonths(i));
                }
                break;

            default:
                // 默认过去7天
                for (int i = 6; i >= 0; i--) {
                    dates.add(today.minusDays(i));
                }
        }

        return dates;
    }
}
